package com.luoshenshen.socker;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * @author ShenshenLuo
 * @date 2025/4/19 17:26
 **/
public class WebSocker {

    public static void main(String[] args) throws InterruptedException {

        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {

                        ChannelPipeline pipeline = ch.pipeline();
                        // 基于http
                        pipeline.addLast(new HttpServerCodec());
                        // 以块方式写入
                        pipeline.addLast(new ChunkedWriteHandler());
                        // 聚合块大小
                        pipeline.addLast(new HttpObjectAggregator(512));
                        // 协议 ws://localhost:88990/
                        pipeline.addLast(new WebSocketServerProtocolHandler("/ss"));

                        pipeline.addLast(new MyWebSockerHandler());
                    }
                });
        ChannelFuture sync = bootstrap.bind(8899).sync();
        ChannelFuture channelFuture = sync.channel().closeFuture();
    }
}
